//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2006
//
// Delete attached file with raster, tracks, waypoints or routes.
//

# include "StdAfx.h"
# include "UndoRedo.h"
# include "DeleteAttachment.h"
# include "Map.h"
# include "Selection.h"
# include "Globals.h"

class CDeleteAttachmentAction : public CEditAction {
  public:
	CDeleteAttachmentAction (file_ref_t * _pFileRef, bool _bRenderer) :
		m_strFileName (_pFileRef->strFileName),
		m_pFileRef (_pFileRef),
		m_pData (NULL),
		m_bRenderer (_bRenderer)
	{}
	virtual ~CDeleteAttachmentAction ();

	virtual void GetName (string_t & _str) const;
	virtual cu_t CanUndo () const {return cuYes;}
	virtual bool Do ();
	virtual void Undo ();
	virtual void Redo () {CDeleteAttachmentAction::Do ();}

  private:
	const string_t m_strFileName;
	file_ref_t * const m_pFileRef;
	void * m_pData;
	const bool m_bRenderer;
};

CDeleteAttachmentAction::~CDeleteAttachmentAction () {
	if (m_pData) {
		assert (m_pFileRef);
		m_pFileRef->FreeData (m_pData);
	}
}

void CDeleteAttachmentAction::GetName (string_t & _str) const {
	CCritSec::CLock lock (g_cs);

	_str.append ("detach [");
	_str.append (m_strFileName);
	_str.append ("]");
}

bool CDeleteAttachmentAction::Do () {
	CCritSec::CLock lock (g_cs);

	assert (m_pFileRef);
	assert (! m_pData);
	m_pData = m_pFileRef->DetachData ();
	m_pFileRef->bDeleted = true;

	if (m_bRenderer)
		UpdateOverlays (g_map.renderers);

	return true;
}

void CDeleteAttachmentAction::Undo () {
	CCritSec::CLock lock (g_cs);

	assert (m_pFileRef);
	m_pFileRef->AttachData (m_pData);
	m_pFileRef->bDeleted = false;
	m_pData = NULL;

	if (m_bRenderer)
		UpdateOverlays (g_map.renderers);
}

////////////////////////////////////////////

void DeleteAttachment (file_ref_t * _pFileRef, bool _bRenderer) {
	PerformEditAction (new CDeleteAttachmentAction (_pFileRef, _bRenderer));
}
